package org.noootsab.gae.games.tzaar.service.impl;

import com.google.appengine.api.datastore.*;
import org.noootsab.gae.games.tzaar.model.*;
import org.noootsab.gae.games.tzaar.service.*;

import java.io.*;
import java.util.Properties;
import javax.jdo.*;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


/**
 * User: sandy
 * Date: 05-avr.-2010
 * Time: 14:23:28
 */
public class MailServiceImpl implements MailService {
    public void turnChanger(String gameKey, String fromPlayerKey, String toPlayerKey) throws UnsupportedEncodingException, MessagingException {
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        PersistenceManager persistenceManager = PersistenceManagerFactoryHelper.get().getPersistenceManager();
        Key k = KeyFactory.stringToKey(gameKey);
        Game game = persistenceManager.getObjectById(Game.class, k);

        String msgBody = String.format("Your opponent has just finish his turn... Check out on http://bg-tzaar.appspot.com/?gameId=%s", game.getGameId());
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("andy.petrella@gmail.com", "Tzaar Game"));
        Player to = persistenceManager.getObjectById(Player.class, KeyFactory.stringToKey(toPlayerKey));
        msg.addRecipient(Message.RecipientType.TO,
                new InternetAddress(to.getEmail().getEmail()));
        msg.setSubject("It's your turn...");
        msg.setText(msgBody);
        Transport.send(msg);
    }

    public String inviteToJoin(String gameKey, String fromEmail, String toEmail) throws UnsupportedEncodingException, MessagingException {
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        PersistenceManager persistenceManager = PersistenceManagerFactoryHelper.get().getPersistenceManager();
        Key k = KeyFactory.stringToKey(gameKey);
        Game game = persistenceManager.getObjectById(Game.class, k);

        String msgBody = String.format("A guy (%s) is asking you to play with him at tzaar. Check it out: http://bg-tzaar.appspot.com/?gameId=%s", fromEmail, game.getGameId());
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("andy.petrella@gmail.com", "Tzaar Game"));
        msg.addRecipient(Message.RecipientType.TO,
                new InternetAddress(toEmail));
        msg.setSubject("Someone is challenging you at tzaar!");
        msg.setText(msgBody);
        Transport.send(msg);
        return toEmail;
    }
}
